﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WeChatIdentity.Models;

namespace IdentityServer.Data.Repositories
{
    public class UserRepository : IUserRepository
    {
        public readonly IdentityServerContext _context;
        private SignInManager<ApplicationUser> _signInManager;
        private UserManager<ApplicationUser> _userManager;
        public UserRepository(IdentityServerContext context,
             SignInManager<ApplicationUser> signInManager,
             UserManager<ApplicationUser> userManager)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _signInManager = signInManager;
            _userManager = userManager;
        }
        public async Task<ApplicationUser> AddUserAsync(ApplicationUser user)
        {
            var addUser = _context.Users.Add(user).Entity;
            await _context.SaveChangesAsync();
            return addUser;
        }
        public void UpdateUser(ApplicationUser user)
        {
            _context.Entry(user).State = EntityState.Modified;
        }
        public async Task<ApplicationUser> GetUserByOpenIdAsync(string openid)
        {
            return await _context.Users.FirstOrDefaultAsync(t => t.OpenId == openid);
        }

        public void UpdateUserClaim(UserClaim claim)
        {
            _context.Entry(claim).State = EntityState.Modified;
        }
        public async Task<IEnumerable<IdentityUserClaim<string>>> GetUserClaimsByUserId(string userId)
        {
            var claims = _context.UserClaims.Where(t => t.UserId == userId);
            return await Task.FromResult(claims);
        }

        public async Task<ApplicationUser> FindByUsername(string user)
        {
            return await _userManager.FindByNameAsync(user);
        }

        public async Task<bool> ValidateCredentialsAsync(ApplicationUser user, string password)
        {
            return await _userManager.CheckPasswordAsync(user, password);
            //return await _context.Users.FirstOrDefaultAsync(t => t.UserName == userName && t.PasswordHash == password);
        }

        public async Task SignIn(ApplicationUser user)
        {
            await _signInManager.SignInAsync(user, true);
        }

        public async Task SignInAsync(ApplicationUser user, AuthenticationProperties properties, string authenticationMethod = null)
        {
             await _signInManager.SignInAsync(user, properties, authenticationMethod);
        }
    }
}
